//
//  UIImage+Border.m
//  MacroTest
//
//  Created by xiaokang on 2017/6/21.
//  Copyright © 2017年 xiaokang. All rights reserved.
//

#import "UIImage+Border.h"

@implementation UIImage (Border)

- (UIImage *)imageWithCornerRadius:(CGFloat)cornerRadius {
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    
    // void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
    //size——同UIGraphicsBeginImageContext,参数size为新创建的位图上下文的大小
    //    opaque—透明开关，如果图形完全不用透明，设置为YES以优化位图的存储。
    //    scale—–缩放因子
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [UIScreen mainScreen].scale);
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
    [path addClip];
    [self drawInRect:rect];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


- (UIImage *)imageWithBorderWith:(CGFloat)borderWith borderColor:(UIColor *)borderColor cornerRadius:(CGFloat)cornerRadius{
    CGSize bg_size = CGSizeMake(self.size.width + 2 * borderWith, self.size.height + 2 * borderWith);
    UIGraphicsBeginImageContextWithOptions(bg_size, NO, 0);
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, bg_size.width, bg_size.height)
                                                    cornerRadius:cornerRadius];
    [borderColor set];
    [path fill];
    path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(borderWith, borderWith, self.size.width, self.size.height)
                                      cornerRadius:cornerRadius];
    [path addClip];
    [self drawInRect:CGRectMake(borderWith, borderWith, self.size.width, self.size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
@end
